/*****************************************************************
 MYD Engine v0.1

 file: myd_game.cpp
 Created: 18/06/09
*****************************************************************/
#include "myd_game.h"
#include "os/myd_window.h"
#include "graphics/myd_renderer.h"
#include "entities/myd_entity.h"
#include "io/myd_importer.h"
#include "timer/myd_timer.h"

using namespace myd;

Game::Game(HINSTANCE hInstance):
wn_window(NULL),
m_hInstance(hInstance),
wn_importer(NULL),
wn_timer(NULL),
physics(),
wn_camera(0,0,-10)
{
}

Game::~Game(void){}

bool Game::init()
{
	if(!m_hInstance)
		return false;

	//create window
	wn_window = new Window();

	if(!wn_window->createWindow(m_hInstance))
		return false;

	//create renderer
	wn_renderer = new Renderer(wn_window->hwnd);
	
	if(!wn_renderer->init())
		return false;

	wn_renderer->setCullMode(D3DCULL_NONE);//<--this goes to tstgame
	wn_renderer->initLight();

	//create loader
	wn_importer = new Importer(wn_renderer);

	//create timer
	wn_timer = new Timer();

	//init input
	input = new DirectInput(m_hInstance, wn_window->hwnd);
	input->Init();

	//user init
	if(!onInit())
		return false;

	//sort entities by etc
	sortEntitiesByDepth();

	//init timer
	wn_timer->firstMeasure();

	return true;
}

bool Game::loop()
{
	assert(wn_renderer);
	assert(wn_timer);

	//update the timer
	wn_timer->measure();

	//update input
	input->Update();

	//update all the entities
	for(unsigned int i=0; i<wn_entities.size(); i++)
	{
		wn_entities[i]->update(wn_timer->getTimeBetweenFrames());
	}

	//check collisions
	physics.checkCollision();
	
	//render the frame
	wn_renderer->beginScene();

	//draw all the entities
	for(unsigned int i=0; i<wn_entities.size(); i++)
	{
		wn_entities[i]->draw(*wn_renderer);
	}

	wn_camera.Draw(wn_renderer);

	//user loop
	bool bQuit = onLoop();

	wn_renderer->endScene();

	return bQuit;
}

bool Game::deinit()
{
	//user deinit
	if(!onDeinit())
		return false;

	//delete engine objects
	delete wn_window;
	wn_window = NULL;
	
	delete wn_importer;
	wn_importer = NULL;

	delete wn_timer;
	wn_timer = NULL;

	return true;
}

void Game::setViewPosition(float x, float y)
{
	wn_renderer->setViewPosition(x, y);
}